<template>
	<view class="content">
		<u-navbar placeholder :bgColor="bgColor" :border="false" autoBack>
			<view slot="center">
				📒 {{ params.name }}
			</view>
		</u-navbar>
		<view v-if="knowledgeBaseType === String(1)" class="btn-bar">
			<u-button class="btn-primary" size="mini" @tap="editNote">编辑笔记</u-button>
			<u-button class="btn-success" size="mini" @tap="editNoteDetail">编辑笔记详情</u-button>
			<u-button class="btn-success" size="mini" @tap="deleteNote">删除笔记</u-button>
		</view>
		<view class="scroll-wrap">
			<scroll-view class="scroll-view_H" bounce="false" enable-back-to-top="false" scroll-y @scrolltolower="loadMore" :lower-threshold="50">
				<view class="note-container">
					<view class="note-li" v-for="(item, i) in list" :key="i">
						<view class="topic-no">{{ item.topicNo }}</view>
						<view class="topic-content">{{ item.topic }}</view>
						<!-- 用户题目显示删除按钮 -->
						<tn-button v-if="knowledgeBaseType === String(1)" @click="removeTopic(item)">删除</tn-button>
					</view>
					<view v-if="loading" class="loading-text">
						加载中...
					</view>
					<view v-if="noMore" class="no-more-text">
						没有更多数据了
					</view>
				</view>
			</scroll-view>
		</view>
		<tn-toast ref="toast"></tn-toast>

		<!-- 编辑笔记弹窗 -->
		<tn-modal v-model="showEditNote" :maskCloseable="false" :showCloseBtn="true" title="编辑笔记" :custom="true"
			class="note-modal">
			<tn-list-view :card="true" unlined="all" class="note-list-view">
				<!-- 笔记名称 -->
				<view class="form-group">
					<label class="form-label" for="edit-note-name">笔记名称</label>
					<tn-input v-model="editNoteForm.name" id="edit-note-name" placeholder="请输入笔记名称" clearable />
				</view>

				<!-- 笔记描述 -->
				<view class="form-group">
					<label class="form-label" for="edit-note-title">笔记描述</label>
					<tn-input v-model="editNoteForm.title" id="edit-note-title" placeholder="请输入笔记描述" clearable />
				</view>
			</tn-list-view>

			<!-- 底部操作按钮 -->
			<view class="action-buttons">
				<tn-button backgroundColor="#409eff" fontColor="#fff" class="btn-save"
					@click="submitEditNote">保存</tn-button>
				<tn-button backgroundColor="#ccc" fontColor="#333" class="btn-cancel"
					@click="showEditNote = false">取消</tn-button>
			</view>
		</tn-modal>

		<!-- 编辑题目详情弹窗 -->
		<tn-modal v-model="showEditNoteDetail" :maskCloseable="false" :showCloseBtn="true" title="查看/编辑笔记题目详情"
			:custom="true" class="note-modal">
			<tn-list-view :card="true" unlined="all" class="note-list-view">
				<!-- 笔记详情内容 -->
				<view class="form-group">
					<label class="form-label">题目列表</label>
					<view v-for="(item, index) in editNoteDetailForm.topicDTOS" :key="item.id" class="topic-item"
						style="margin-bottom: 16rpx;">
						<!-- 题号 -->
						<view class="topic-no" style="font-weight: 700; font-size: 28rpx; margin-bottom: 6rpx;">
							题目 {{ editNoteDetailForm.topicDTOS[index].topicNo }}
						</view>
						<tn-input v-model="editNoteDetailForm.topicDTOS[index].topic" type="textarea" :height="150"
							:placeholder="`请输入第 ${index + 1} 个题目内容`" clearable />
						<tn-input v-model="editNoteDetailForm.topicDTOS[index].answer" type="textarea" :height="150"
							:placeholder="`请输入题目答案`" clearable />
					</view>
					<!-- 如果需要可以加按钮支持新增题目 -->
					<u-button size="small" type="primary" @tap="addTopicItem">新增题目</u-button>
				</view>
			</tn-list-view>


			<!-- 底部操作按钮 -->
			<view class="action-buttons">
				<tn-button backgroundColor="#409eff" fontColor="#fff" class="btn-save"
					@click="submitEditNoteDetail">保存</tn-button>
				<tn-button backgroundColor="#ccc" fontColor="#333" class="btn-cancel"
					@click="showEditNoteDetail = false">取消</tn-button>
			</view>
		</tn-modal>

		<!-- 删除笔记弹窗 -->
		<tn-modal v-model="showDeleteModal" title="确认删除" :showCancelButton="false" :showConfirmButton="false"
			class="note-modal" :custom="true">
			<view>是否确认删除该笔记？</view>

			<!-- 自定义底部操作按钮 -->
			<view class="action-buttons" style="margin-top: 40rpx; display: flex; justify-content: space-around;">
				<tn-button backgroundColor="#fa3534" fontColor="#fff" @click="confirmDeleteNote">删除</tn-button>
				<tn-button backgroundColor="#ccc" fontColor="#333" @click="showDeleteModal = false">取消</tn-button>
			</view>
		</tn-modal>



	</view>

</template>

<script>
	import noteInfo from '@/api/index.js';
	import loginInfo from '@/api/login.js';
	export default {
		data() {
			return {
				bgColor: "transparent",
				list: [], // 数据列表
				page: 1, // 当前页码
				pageSize: 10, // 每页条数
				loading: false, // 是否正在加载
				noMore: false, // 是否没有更多数据
				params: {
					id: '',
					name: '',
					type: ''
				},
				knowledgeBaseType: '',
				noteId: '',

				showEditNote: false,
				showEditNoteDetail: false,
				editNoteForm: {
					name: '',
					title: ''
				},
				editNoteDetailForm: {
					topicDTOS: []
				},

				showDeleteModal: false, // 控制弹窗
				currentNoteId: null, // 当前操作的笔记ID
				
				knowledgeBaseName: '',
				knowledgeBaseId: ''
			}
		},
		onLoad(options) {
			if (options.params) {
				let obj = JSON.parse(decodeURIComponent(options.params));
				this.params.id = obj.id;
				this.noteId = obj.id;
				this.params.name = obj.name;
				this.params.type = obj.type;
				this.knowledgeBaseType = obj.type;
				this.knowledgeBaseName = obj.knowledgeBaseName;
				this.knowledgeBaseId = obj.knowledgeBaseId;
			}
		},
		onReady() {},
		mounted() {
			this.getList(); // 初始化加载数据
		},
		onShow() {
			this.getList(); // 每次页面重新展示时自动刷新
		},

		methods: {

			// 删除笔记
			deleteNote() {
				// 假设你当前页面有传入笔记id，可以直接使用
				this.showDeleteModal = true;
				this.currentNoteId = this.noteId; // 例如 props 传入 noteId
			},
			// 确认删除笔记
			async confirmDeleteNote() {
				try {
					const res = await noteInfo.deleteBatchNoteApi([this.currentNoteId]);
					if (res.data.code === 200) {
						this.$u.toast('删除成功');
						this.showDeleteModal = false;
						const data = {
						        id: this.knowledgeBaseId,
						        name: this.knowledgeBaseName,
						        type: this.knowledgeBaseType
						      };
						await this.goKnowledgeDetail(data);

					} else {
						this.$u.toast(res.data.message || '删除失败');
						this.showDeleteModal = false;
					}
				} catch (err) {
					this.$u.toast('系统异常');
					this.showDeleteModal = false;
				}
			},
			
			// 重定向！到知识库详情页
			goKnowledgeDetail(data) {
				const paramObj = {
					id: data.id,
					name: data.name,
					type: data.knowledgeType
				}
				uni.redirectTo({
					url: './knowledgeDetail?params=' + encodeURIComponent(JSON.stringify(paramObj))
				})
			},

			// 删除题目
			async removeTopic(item) {
				const confirm = await uni.showModal({
					title: '提示',
					content: '是否确认删除该题目？',
					confirmText: '删除',
					cancelText: '取消'
				});

				if (confirm.confirm) {
					const res = await noteInfo.deleteTopicApi([item.id]);
					if (res.data.code === 200) {
						console.log("res: ",res)
						// 成功后前端移除该项
						// this.topicDTOS = this.topicDTOS.filter(t => t.id !== item.id);

						uni.showToast({
							title: '删除成功',
							icon: 'success'
						});
						setTimeout(() => {
						  uni.navigateBack();
						}, 1000); 
						
					} else {
						uni.showToast({
							title: '删除失败，请重试！',
							icon: 'none'
						});
					}
				}
			},


			// 新增题目框
			addTopicItem() {
				const lastTopicNo = this.editNoteDetailForm.topicDTOS.length > 0 ?
					Number(this.editNoteDetailForm.topicDTOS[this.editNoteDetailForm.topicDTOS.length - 1].topicNo) :
					0;

				this.editNoteDetailForm.topicDTOS.push({
					noteType: 1,
					topic: '',
					topicNo: lastTopicNo + 1,
					userNoteId: this.noteId,
					topicId: this.noteId,
					answer: '',
					status: 1,
					type: uni.getStorageSync('bindType')
				});
			},

			// 打开编辑笔记弹窗
			editNote() {
				this.editNoteForm.name = this.params.name;
				this.editNoteForm.title = ''; // 你可以从接口加载描述
				this.showEditNote = true;
			},
			// 打开编辑详情弹窗
			editNoteDetail() {
				if (this.list.length > 0) {
					// 直接复制题目列表到编辑表单
					this.editNoteDetailForm.topicDTOS = this.list.map(item => ({
						id: item.id,
						topic: item.topic,
						topicNo: item.topicNo,
						userNoteId: this.noteId,
						topicId: this.noteId,
						answer: item.answer,
						status: 1,
						type: uni.getStorageSync('bindType')
					}));
				} else {
					// 没有内容时，初始化一个空的题目列表，方便用户新增
					this.editNoteDetailForm.topicDTOS = [];
				}
				this.showEditNoteDetail = true;
			},
			// 保存笔记修改
			async submitEditNote() {
				try {
					// 调用保存接口
					await noteInfo.updateNoteApi({
						id: this.params.id,
						name: this.editNoteForm.name,
						title: this.editNoteForm.title
					});
					this.params.name = this.editNoteForm.name;
					this.showEditNote = false;
					this.$refs.toast.show({
						title: '保存成功',
						type: 'success'
					});
					// 返回到知识库页面
					setTimeout(() => {
					  uni.navigateBack();
					}, 1000); 
				} catch (e) {
					this.$refs.toast.show({
						title: '保存失败',
						type: 'error'
					});
				}
			},
			// 保存详情修改
			async submitEditNoteDetail() {
				try {
					// 根据你的后端接口适配
					await noteInfo.updateNoteDetailApi({
						id: this.editNoteDetailForm.id,
						noteType: 1,
						noteId: this.params.id,
						topicDTOS: this.editNoteDetailForm.topicDTOS
					});
					this.showEditNoteDetail = false;
					this.$refs.toast.show({
						title: '保存成功',
						type: 'success'
					});
					await this.refreshList();
				} catch (e) {
					this.$refs.toast.show({
						title: '保存失败',
						type: 'error'
					});
				}
			},
			// 刷新笔记题目列表
			async refreshList() {
				this.page = 1;
				this.noMore = false;
				this.list = [];
				await this.getList();
			},




			// 获取数据
			async getList() {
				if (this.noMore || this.loading) return;
				this.loading = true;
				try {
					const queryData = {
						pageQueryDTO: {
							currentPage: this.page,
							pageSize: this.pageSize
						},
						userId: uni.getStorageSync('userId'),
						type: uni.getStorageSync('bindType'),
						systemNoteId: '',
						userNoteId: ''
					}
					let res;
					if (this.params.type == 0) {
						queryData.systemNoteId = this.params.id,
							res = await noteInfo.getNoteSystemQueryApi(this.params.id, queryData);
					} else {
						queryData.userNoteId = this.params.id,
							res = await noteInfo.getNoteUserQueryApi(this.params.id, queryData);
					}
					if (res.data.code == 200) {
						if (this.page === 1) {
							this.list = [...res.data.data.pageResultDTO?.content];
						} else {
							this.list = [...this.list, ...res.data.data.pageResultDTO?.content];
						}
						if (res.data.data.pageResultDTO.content.length < this.pageSize) {
							this.noMore = true;
						} else {
							this.page++;
						}
					}
				} catch (error) {
					console.error("加载失败:", error);
				} finally {
					this.loading = false;
				}
			},
			// 上拉加载更多
			loadMore() {
				this.getList();
			},
			onSelect(e) {
				const {
					name,
					value
				} = e
				this.formData[name] = value
			},
			goChooseQuestions() {
				uni.navigateTo({
					url: './chooseQuestions'
				})
			}
		}
	}
</script>
<style lang="scss" scoped>
	
	.btn-bar {
		display: flex;
		justify-content: flex-end;
		gap: 20rpx;
		padding: 20rpx 32rpx;
		background: rgba(255, 255, 255, 0.3);
		backdrop-filter: blur(10px);
		border-radius: 20rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
	}

	.btn-primary {
		background: #409eff;
		/* 清爽蓝色 */
		border-radius: 16rpx;
		box-shadow: 0 2rpx 6rpx rgba(64, 158, 255, 0.5);
		color: white;
		font-weight: 600;
		transition: transform 0.2s ease, box-shadow 0.2s ease;
	}

	.btn-primary:hover,
	.btn-primary:active {
		transform: translateY(-2rpx);
		box-shadow: 0 6rpx 14rpx rgba(64, 158, 255, 0.7);
	}

	.btn-success {
		background: #67c23a;
		/* 清新绿色 */
		border-radius: 16rpx;
		box-shadow: 0 2rpx 6rpx rgba(103, 194, 58, 0.5);
		color: white;
		font-weight: 600;
		transition: transform 0.2s ease, box-shadow 0.2s ease;
	}

	.btn-success:hover,
	.btn-success:active {
		transform: translateY(-2rpx);
		box-shadow: 0 6rpx 14rpx rgba(103, 194, 58, 0.7);
	}



	.note-modal {
		max-width: 600rpx;
		height: 60vh;
		/* 固定高度 */
		border-radius: 16rpx;
		padding: 32rpx 24rpx;

		display: flex;
		flex-direction: column;
	}


	/* 内容区撑满剩余空间，超出可滚动 */
	.note-list-view {
		flex: 1;
		overflow-y: auto;
		margin-bottom: 24rpx;
	}

	.form-group {
		margin-bottom: 24rpx;
		display: flex;
		flex-direction: column;
	}

	.form-label {
		font-weight: 600;
		font-size: 28rpx;
		margin-bottom: 8rpx;
	}

	/* 底部按钮区域固定 */
	.action-buttons {
		flex-shrink: 0;
		/* 不被压缩 */
		display: flex;
		justify-content: center;
		gap: 24rpx;
	}

	.btn-save {
		flex: 1;
		padding: 16rpx 0;
		border-radius: 12rpx;
	}

	.btn-cancel {
		flex: 1;
		padding: 16rpx 0;
		border-radius: 12rpx;
	}




	.scroll-wrap {
		flex: 1; /* 占满剩余空间 */
		overflow: hidden;
		width: 100%;
		height: calc(100vh - 200rpx);
		min-height: 300rpx; // 防止极端视口过小时塌陷

		.scroll-view_H {
			height: 100%;

			.note-container {
				min-height: 100%;
				display: flex;
				flex-direction: column;
				padding: 32rpx;
				box-sizing: border-box;
				gap: 24rpx; // 稍大间距更清爽
			}

			.note-li {
				display: flex;
				align-items: flex-start;
				background: #fff;
				border-radius: 16rpx;
				padding: 24rpx 28rpx;
				box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
				overflow: hidden;
				transition: box-shadow 0.3s ease, transform 0.3s ease;
				cursor: pointer;
				user-select: text;

				&:hover,
				&:active {
					box-shadow: 0 8rpx 28rpx rgba(0, 0, 0, 0.12);
					transform: translateY(-2rpx);
				}
			}

			.topic-no {
				width: 90rpx;
				font-weight: 700;
				font-size: 30rpx;
				color: #4a4a4a; // 深灰色，避免纯黑突兀
				flex-shrink: 0;
				margin-right: 24rpx;
				user-select: none;
				line-height: 1.2;
				text-align: center;
			}

			.topic-content {
				flex: 1;
				font-size: 30rpx;
				color: #555;
				word-break: break-word;
				white-space: normal;
				line-height: 1.5;
				-webkit-font-smoothing: antialiased; // 文字抗锯齿
				-moz-osx-font-smoothing: grayscale;
			}

			.loading-text,
			.no-more-text {
				width: 100%;
				text-align: center;
				display: flex;
				justify-content: center;
				padding: 28rpx 0;
				color: #999;
				font-size: 28rpx;
				font-weight: 500;
				user-select: none;
			}
		}
	}
</style>